package com.aisino.mvpdesignproject2.ui.base.activity;

import android.os.Bundle;
import android.view.View;

import com.aisino.mvpdesignproject2.http.itf.Stateful;
import com.aisino.mvpdesignproject2.ui.model.BaseModel;
import com.aisino.mvpdesignproject2.ui.presenter.BasePresenter;
import com.aisino.mvpdesignproject2.view.LoadingPage;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseActivity<T extends BasePresenter> extends SwipeBackActivity implements Stateful{
    public LoadingPage mLoadingPage;
    //只加载一次界面
    private boolean isFirst = true;
    protected View contentView;
    private Unbinder bind;
    public T presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mLoadingPage == null) {
            mLoadingPage = new LoadingPage(this) {
                @Override
                protected void initView() {
                    if (isFirst) {
                        BaseActivity.this.contentView = this.contentView;
                        bind = ButterKnife.bind(BaseActivity.this, contentView);
                        BaseActivity.this.initView();
                        isFirst = false;
                    }
                }

                @Override
                protected void loadData() {
                    BaseActivity.this.loadData();
                }

                @Override
                protected int getLayoutId() {
                    return BaseActivity.this.getLayoutId();
                }
            };
        }
        setContentView(mLoadingPage);

        presenter = (T) new BaseModel();
        presenter.setStateful(this);

    }

    /**
     * 3
     * 子类关于View的操作(如setAdapter)都必须在这里面，会因为页面状态不为成功，而binding还没创建就引用而导致空指针。
     * loadData()和initView只执行一次，如果有一些请求需要二次的不要放到loadData()里面。
     */
    protected abstract void initView();

    /**
     * 1
     * 根据网络获取的数据返回状态，每一个子类的获取网络返回的都不一样，所以要交给子类去完成
     */
    protected abstract void loadData();

    /**
     * 2
     * 网络请求成功在去加载布局
     *
     * @return
     */
    protected abstract int getLayoutId();

    @Override
    public void setState(int state) {
        mLoadingPage.state = state;
        mLoadingPage.showPage();
    }
}
